// 初始化插件状态
chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.local.set({ enabled: true });
});

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "getState") {
    chrome.storage.local.get(['enabled'], (result) => {
      sendResponse({ enabled: result.enabled !== false });
    });
    return true;
  } else if (request.action === "toggleState") {
    chrome.storage.local.get(['enabled'], (result) => {
      const newState = !result.enabled;
      chrome.storage.local.set({ enabled: newState }, () => {
        // 通知所有标签页状态改变
        chrome.tabs.query({}, (tabs) => {
          tabs.forEach(tab => {
            try {
              chrome.tabs.sendMessage(tab.id, { 
                action: "stateChanged", 
                enabled: newState 
              }).catch(() => {
                // 忽略无法发送消息的标签页
              });
            } catch (e) {
              // 忽略不支持的标签页
            }
          });
        });
        sendResponse({ enabled: newState });
      });
    });
    return true;
  }
});
